<template>
  <div class="task_form_dialog">
    <el-dialog
      v-model="visible"
      :title="`${isEdit ? '编辑' : '新建'}任务`"
      :append-to-body="true"
      :show-close="false"
      :close-on-click-modal="false"
      top="3vh"
      center
      width="800px"
    >
      <div v-loading="dialogLoading" class="dialog_container">
        <div class="form_box f_1">
          <el-form
            ref="formRef"
            :rules="rules"
            :model="form"
            label-width="110px"
            size="small"
          >
            <el-form-item label="版本" prop="releaseId">
              <el-select
                v-model="form.releaseId"
                placeholder="请选择"
                size="small"
              >
                <el-option
                  v-for="item in prepareData.releaseIdSelectList"
                  :key="item.id"
                  :label="item.releaseName"
                  :value="item.id"
                >
                </el-option>
              </el-select>
              <el-button
                size="mini"
                type="text"
                @click="editReleaseSelect"
                style="margin-left: 20px"
              >
                编辑
              </el-button>
            </el-form-item>

            <el-form-item label="模块" prop="moduleIds">
              <ProjectModuleCascade
                ref="projectModuleCascadeRef"
                :moduleNames="form.moduleNames"
                @change="changeModuleIds"
              />
            </el-form-item>

            <el-form-item label="优先级" prop="taskPriority">
              <el-select
                v-model="form.taskPriority"
                placeholder="请选择"
                size="small"
              >
                <el-option
                  v-for="item in prepareData.taskPrioritySelectList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="任务状态" prop="taskStatus">
              <el-select
                v-model="form.taskStatus"
                placeholder="请选择"
                size="small"
                :disabled="true"
              >
                <el-option
                  v-for="item in prepareData.taskStatusSelectList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="任务标题" prop="taskTitle">
              <el-input
                v-model="form.taskTitle"
                size="small"
                placeholder="请输入"
              ></el-input>
            </el-form-item>

            <el-form-item label="任务说明" prop="taskDesc">
              <!-- 富文本 -->
              <RichEditor v-model="form.taskDesc" :height="150" />
            </el-form-item>

            <el-form-item label="任务备注" prop="taskRemark">
              <el-input
                v-model="form.taskRemark"
                size="small"
                placeholder="请输入"
              ></el-input>
            </el-form-item>

            <el-form-item label="需求评审时间" prop="demandAuditTime">
              <el-date-picker
                v-model="form.demandAuditTime"
                type="date"
                value-format="YYYY-MM-DD"
                placeholder="选择日期"
                size="small"
              ></el-date-picker>
            </el-form-item>

            <!-- 显示有创建需求权限的用户列表，默认填充当前登录人 -->
            <el-form-item label="需求负责人" prop="demandUserId">
              <el-select
                v-model="form.demandUserId"
                placeholder="请选择"
                size="small"
              >
                <el-option
                  v-for="item in demandUserSelectList"
                  :key="item.id"
                  :label="item.truename"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-form>
        </div>
      </div>
      <template #footer>
        <div class="dialog_footer">
          <el-button
            type="primary"
            @click="handleConfirm"
            :loading="confirmBtnLoading"
            size="small"
          >
            保存
          </el-button>
          <el-button @click="close" size="small">关闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, nextTick, getCurrentInstance } from "vue";
import { useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import RichEditor from "../../../components/RichEditor.vue";
import ProjectModuleCascade from "../../../components/ProjectModuleCascade.vue";

const initFormData = () => {
  return {
    id: null,
    releaseId: null,
    moduleIds: null,
    moduleNames: null,
    taskPriority: null,
    taskStatus: null,
    taskTitle: null,
    taskDesc: null,
    taskRemark: null,
    demandUserId: null,
    demandAuditTime: null,
  };
};

export default {
  name: "TaskFormDialog",
  components: { ProjectModuleCascade, RichEditor },
  props: {
    // 预加载数据
    prepareData: {
      type: Object,
      default: () => {
        return {
          taskStatusSelectList: [],
          releaseIdSelectList: [],
          taskPrioritySelectList: [],
        };
      },
    },
  },
  setup(props, context) {
    const { proxy } = getCurrentInstance();
    const $api = proxy.$api;
    const router = useRouter();

    const isEdit = ref(false);
    // 弹框是否显示
    const visible = ref(false);
    // 是否开启整个弹框loading（开启时无法关闭弹框）
    const dialogLoading = ref(false);
    // 确认按钮loading（开启时可以关闭弹框）
    const confirmBtnLoading = ref(false);
    // 表单的引用
    const formRef = ref(null);
    // 级联组件的引用
    const cascaderRef = ref(null);
    // 表单数据
    const form = reactive(initFormData());
    // 表单校验规则
    const rules = reactive({
      // moduleIds: [{
      //   required: true,
      //   trigger: "blur",
      //   validator: (rule, value, callback) => {
      //     let choose = cascaderRef.value.getCheckedNodes();
      //     if (!choose.length) {
      //         callback(new Error('请选择模块名称'))
      //     } else {
      //         callback()
      //     }
      //   }
      // }],
      releaseId: [{ required: true, message: "请选择版本", trigger: "blur" }],
      taskPriority: [
        { required: true, message: "请选择优先级", trigger: "blur" },
      ],
      taskTitle: [
        { required: true, message: "请输入任务标题", trigger: "blur" },
      ],
      demandAuditTime: [
        { required: true, message: "请选择需求评审时间", trigger: "blur" },
      ],
      demandUserId: [
        { required: true, message: "请选择需求负责人", trigger: "blur" },
      ],
    });

    const projectModuleCascadeRef = ref(null);

    // 有创建需求权限的用户列表
    const demandUserSelectList = ref([]);

    // 选择模块
    const changeModuleIds = ({ moduleIds, moduleNames }) => {
      console.log("changeModuleIds => ", { moduleIds, moduleNames });
      if (moduleIds && moduleNames) {
        form.moduleIds = moduleIds;
        form.moduleNames = moduleNames;
      }
    };

    const handleConfirm = () => {
      formRef.value.validate((valid) => {
        if (valid) {
          confirmBtnLoading.value = true;
          $api.task
            .saveOrUpdate(form)
            .then((res) => {
              confirmBtnLoading.value = false;
              ElMessage.success("操作成功！");
              // 触发事件，把数据传递给父组件
              context.emit("refresh");
              close();
            })
            .catch((err) => {
              confirmBtnLoading.value = false;
              console.error("saveOrUpdate error: ", err);
            });
        } else {
          return false;
        }
      });
    };

    // 打开弹框
    const open = (row) => {
      if (row) {
        Object.keys(form).forEach((item) => {
          form[item] = row[item];
        });
        isEdit.value = true;
      } else {
        isEdit.value = false;
        if (!props.prepareData.taskStatusSelectList) {
          return ElMessage.warning("关键数据未获取到，请关闭重新打开页面");
        }
        form.taskStatus = props.prepareData.taskStatusSelectList[0].value;
      }
      getDemandUserSelectList();
      visible.value = true;
    };

    // 关闭弹框
    const close = () => {
      if (confirmBtnLoading.value || dialogLoading.value) {
        return;
      }
      resetData();
      visible.value = false;
    };

    // 重置数据
    const resetData = () => {
      // 重置表单校验
      formRef.value && formRef.value.resetFields();
      // 清空级联
      nextTick(() => {
        projectModuleCascadeRef.value && projectModuleCascadeRef.value.clear();
      });
      // 重置表单数据
      Object.keys(form).forEach((item) => {
        form[item] = initFormData()[item];
      });
    };

    // 编辑版本
    const editReleaseSelect = () => {
      // 二次确认删除
      ElMessageBox.confirm(
        `此操作将会离开此页面，未保存的数据将清空，确定要执行吗？`,
        "提示",
        {
          type: "warning",
        }
      )
        .then(() => {
          close();
          router.push("/ReleaseManage");
        })
        .catch(() => {});
    };

    // 获取任务预加载数据
    const getDemandUserSelectList = () => {
      dialogLoading.value = true;
      $api.users
        .listPage()
        .then((res) => {
          demandUserSelectList.value = res.data.list;
        })
        .catch((err) => {
          console.error("getDemandUserSelectList error: ", err);
        })
        .finally(() => {
          dialogLoading.value = false;
        });
    };

    return {
      visible,
      dialogLoading,
      confirmBtnLoading,
      formRef,
      cascaderRef,
      form,
      rules,
      open,
      close,
      projectModuleCascadeRef,
      changeModuleIds,
      handleConfirm,
      editReleaseSelect,
      demandUserSelectList,
      isEdit,
    };
  },
};
</script>

<style lang="less" scoped>
.task_form_dialog {
}
.dialog_container {
}
.dialog_footer {
}
</style>
